package com.store;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

// 演示例子，执行 main 生产目录
public class CodeGenerator {


    //表名称
    static String tableName = "f_user";
    //前面保持不变，最后请自定义包路径的名称
    static String parent = "com.store";  //包路径

    // 业务是否与工作流相关联，true表示与工作流相关的，实体类集成在 ProcessBusinessBaseEntity，会默认带上标题，
    // 是否正文附件，等等业务
    //  false表示不与工作流相关的，实体类继承自 BaseEntity
    static boolean isActiviti = true;

    //模块名称，执行此main函数之前，请务必确保已经新建了模块
    static String module = "/store-system";
    //代码的路径，基本上不需要改动
    static String basePath = "/src/main/java";
    //mapper.xml文件的路径，基本上不需要改动
    static  String mapperXmlbasePath = "/src/main/resources";

    //数据库地址账号密码
    static  String dbUrl = "jdbc:mysql://localhost:3306/fruits?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true";
    static String username = "root";
    static String password = "";

    public static void main(String[] args) {

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
        String author = System.getProperty("user.name");
        gc.setOutputDir(projectPath + module + basePath);
        gc.setAuthor(author);
        gc.setOpen(false);
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dbUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
//        pc.setModuleName(moduleName);
        pc.setParent(parent);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        final String[] entityName = new String[1];
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                entityName[0] = tableInfo.getEntityName();
                return projectPath + module + mapperXmlbasePath  +File.separator + "/mapper"
//                return projectPath + module + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录，自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在，不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setEntity("templates/entity.java");
//        templateConfig.setService("templates/service.java");
//        templateConfig.setController("templates/controller.java");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        String superEntityCalss = "com.ctsi.hndx.common.ProcessBusinessBaseEntity";
        if(!isActiviti){
            superEntityCalss = "com.ctsi.hndx.common.BaseEntity";
            strategy.setSuperEntityColumns("id","update_by","update_name","update_time",
                    "create_by","create_name","create_time","department_id","company_id","tenant_id","deleted");
        }else {
            strategy.setSuperEntityColumns("id","update_by","update_name","update_time",
                    "create_by","create_name","create_time","department_id","company_id","tenant_id","deleted",
                    "title","bpm_status","document","annex","processs_instance_id");
        }

        strategy.setSuperEntityClass(superEntityCalss);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
//        strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
//        strategy.setSuperServiceClass("com.ctsi.hndx.common.SysBaseServiceI");
//        strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        //strategy.setSuperEntityColumns("id");
        //strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setInclude(tableName);
        strategy.setControllerMappingHyphenStyle(true);

        strategy.setLogicDeleteFieldName("deleted");
        //   strategy.setTablePrefix(profix+pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();

        produceViewObject(projectPath,entityName[0] );
    }


    /**
     * 根据表名生成VO对象,用于mybatis-plus代码生成以后再生成
     *
     * @param projectPath
     * @param entityName
     */
    private static void produceViewObject(String projectPath,String entityName) {
        String entityPath = projectPath + module + basePath  +File.separator + parent.replace(".", "/") + "/entity/";

            try {
                File outFile = new File(entityPath+"dto/");
                if (!outFile.exists()) {
                    outFile.mkdirs();
                }
                File voFile = new File(outFile, entityName + "DTO.java");
                if (!voFile.exists()) {
                    voFile.createNewFile();
                }
                BufferedReader reader = new BufferedReader(
                        new FileReader(entityPath + entityName+".java"));
                FileWriter fw = new FileWriter(voFile);
                String line = null;
                while ((line = reader.readLine()) != null) {
                    // 将实体类中的entity变为Vo
                    line = line.replace(entityName, entityName+"DTO");
                    // 去掉mybatis-plus注解
                    if (line.contains("TableName") || line.contains("TableField") || line.contains("Accessors")) {
                        continue;
                    }

                    if (line.contains( "package " + parent+".entity.") ) {
                        continue;
                    }
                    line = line.replace("package " + parent+".entity", "package " + parent+".entity.dto");
                    if (isActiviti){
                        line = line.replace("BaseEntity", "ProcessBusinessBaseDtoEntity");
                    }else {
                        line = line.replace("BaseEntity", "BaseDtoEntity");
                    }

                    line += "\r\n";
                    fw.write(line);
                }
                fw.close();
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

//    /**
//     * <p>
//     * 读取控制台内容
//     * </p>
//     */
//    public static String scanner(String tip) {
//        Scanner scanner = new Scanner(System.in);
//        StringBuilder help = new StringBuilder();
//        help.append("请输入" + tip + "：");
//        System.out.println(help.toString());
//        if (scanner.hasNext()) {
//            String ipt = scanner.next();
//            if (StringUtils.isNotBlank(ipt)) {
//                return ipt;
//            }
//        }
//        throw new MybatisPlusException("请输入正确的" + tip + "！");
//    }
}